import {getUsers, getMenus, getDepts, getPosts, getRoles} from "@/services/system/SysCommon";
import {arr2tree} from "@/utils/utils";

export default {
  namespace: 'SystemCommon',

  state: {
    userList: [],
    menuTree: [],
    deptList: [],
    deptTree: [],
    postList: [],
    roleList: [],
  },

  effects: {
    * getUsers({payload}, {call, put}) {
      const response = yield call(getUsers, payload);
      if (response.code === 0) {
        yield put({
          type: 'chgUserList',
          payload: response.data.map(d => {
            d.key = d.id;
            d.value = d.id;
            d.label = d.nickname;
            return d;
          }),
        });
      }
    },

    * getMenus({payload}, {call, put}) {
      const response = yield call(getMenus, payload);
      if (response.code === 0) {
        yield put({
          type: 'chgMenuTree',
          payload: arr2tree(response.data.map(d => {
            d.label = d.menuName;
            d.value = d.id;
            d.key = d.id;
            return d;
          })),
        });
      }
    },

    * getDepts({payload}, {call, put}) {
      const response = yield call(getDepts, payload);
      if (response.code === 0) {
        yield put({
          type: 'chgDeptList',
          payload: response.data,
        });
        yield put({
          type: 'chgDeptTree',
          payload: arr2tree(response.data.map(d => {
            d.label = d.name;
            d.value = d.id;
            d.key = d.id;
            return d;
          })),
        });
      }
    },

    * getPosts({payload}, {call, put}) {
      const response = yield call(getPosts, payload);
      if (response.code === 0) {
        yield put({
          type: 'chgPostList',
          payload: response.data.map(d => {
            d.value = d.id;
            d.label = d.postName;
            return d;
          }),
        });
      }
    },

    * getRoles({payload}, {call, put}) {
      const response = yield call(getRoles, payload);
      if (response.code === 0) {
        yield put({
          type: 'chgRoleList',
          payload: response.data.map(d => {
            d.value = d.id;
            d.label = d.roleName;
            return d;
          }),
        });
      }
    },

  },

  reducers: {
    chgUserList(state, action) {
      return {
        ...state,
        userList: action.payload,
      };
    },

    chgMenuTree(state, action) {
      return {
        ...state,
        menuTree: action.payload,
      };
    },

    chgDeptList(state, action) {
      return {
        ...state,
        deptList: action.payload,
      };
    },

    chgDeptTree(state, action) {
      return {
        ...state,
        deptTree: action.payload,
      };
    },

    chgPostList(state, action) {
      return {
        ...state,
        postList: action.payload,
      };
    },

    chgRoleList(state, action) {
      return {
        ...state,
        roleList: action.payload,
      };
    },

  }

}